<?php
/**
 * iView Bos 文件上传
 *
 * Author: Zeon
 * Date: 2018/1/27
 * Created by Panxsoft.
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\IViewFileUpload\FileStoreRequest;
use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;

class IViewFileUploadController extends ApiController
{
    use Bosable;

    const BOS_KEY_PREFIX = 'admin-upload-files/';

    /**
     * 前端使用 iview file upload 组件上传文件，返回 url
     *
     * @param FileStoreRequest $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(FileStoreRequest $request)
    {
        $url = $this->uploadFileToUrl($request->file, $request->bos_dir);

        return $this->response(compact('url'));
    }

    /**
     * @param UploadedFile $file
     * @param string $dir
     * @return mixed
     * @throws \Exception
     */
    private function uploadFileToUrl(UploadedFile $file, ?string $dir)
    {
        $bos_key = $this->uploadPostFile($file, $this->normalizeRequestBosDir($dir));

        $url = $this->getStaticUrl($bos_key);

        return $url;
    }

    /**
     * @param string $dir
     * @return string
     */
    private function normalizeRequestBosDir(?string $dir): string
    {
        return $dir ?: self::BOS_KEY_PREFIX;
    }

    /**
     * 用 url 删除对应的 bos key 文件
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy(Request $request)
    {
        $url = $request->url;
        $key = (new BosCleanObserver)->httpUrlToBosKey($url);
            $this->checkUnless($key === $url, trans('admin.not_found_bos_key'));

        $deleted = $this->deleteBosKey($key);

        return $this->response(compact('deleted'));
    }
}
